package com.ruoyi.system.controller;

import java.io.File;
import java.io.IOException;
import java.util.*;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysAppInfo;
import com.ruoyi.system.service.ISysAppInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * APP版本管理Controller
 *
 * @author shuyan
 * @date 2021-09-15
 */
@RestController
@RequestMapping("/system/appInfo")
public class SysAppInfoController extends BaseController {

    @Autowired
    private ISysAppInfoService sysAppInfoService;

    /**
     * 查询APP版本管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysAppInfo sysAppInfo) {
        startPage();
        List<SysAppInfo> list = sysAppInfoService.queryList(sysAppInfo);
        return getDataTable(list);
    }

    /**
     * 导出APP版本管理列表
     */
    @Log(title = "APP版本管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysAppInfo sysAppInfo) {
        List<SysAppInfo> list = sysAppInfoService.queryList(sysAppInfo);
        ExcelUtil<SysAppInfo> util = new ExcelUtil<SysAppInfo>(SysAppInfo.class);
        return util.exportExcel(list, "APP版本管理数据");
    }

    /**
     * 获取APP版本管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(sysAppInfoService.getById(id));
    }

    /**
     * 新增APP版本管理
     */
    @Log(title = "APP版本管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAppInfo sysAppInfo) {
        sysAppInfo.setCreateBy(SecurityUtils.getUsername());
        sysAppInfo.setCreateTime(new Date());
        return toAjax(sysAppInfoService.save(sysAppInfo));
    }

    /**
     * 修改APP版本管理
     */
    @Log(title = "APP版本管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAppInfo sysAppInfo) {
        sysAppInfo.setUpdateBy(SecurityUtils.getUsername());
        sysAppInfo.setUpdateTime(new Date());
        return toAjax(sysAppInfoService.updateById(sysAppInfo));
    }

    /**
     * 删除APP版本管理
     */
    @Log(title = "APP版本管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysAppInfoService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 导入模板
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<SysAppInfo> util = new ExcelUtil<SysAppInfo>(SysAppInfo.class);
        return util.importTemplateExcel("APP版本管理");
    }

    /**
     * 导入数据
     *
     * @param file          文件
     * @param updateSupport 是否覆盖更新
     * @param extraParams   额外参数  JSON字符
     */
    @Log(title = "APP版本管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String extraParams) throws Exception {
        ExcelUtil<SysAppInfo> util = new ExcelUtil<SysAppInfo>(SysAppInfo.class);
        List<SysAppInfo> excelList = util.importExcel(file.getInputStream());
        String message = sysAppInfoService.importData(excelList, updateSupport, extraParams);
        return AjaxResult.success(message);
    }

    /**
     * 检查更新
     */
    @RequestMapping("/checkUpdate")
    public AjaxResult checkUpdate(String version) {
        SysAppInfo appInfo = sysAppInfoService.getAppData();
        Map<String, Object> map = new HashMap<String, Object>();
        //是否应该更新
        map.put("shouldUpdate", !version.equals(appInfo.getVersion()));
        map.put("appInfo", appInfo);
        return AjaxResult.success(map);
    }

    /**
     * 下载App
     */
    @RequestMapping("/updateApp")
    public void updateApp(HttpServletResponse response) {
        SysAppInfo appInfo = sysAppInfoService.getAppData();
        //如果有cdn路径，使用cdn地址，否则使用系统地址
        if (StrUtil.isNotEmpty(appInfo.getCdnPath())) {
            try {
                response.sendRedirect(appInfo.getCdnPath());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            //文件路径
            String fileRelativeName = appInfo.getFilePath().replaceAll(Constants.RESOURCE_PREFIX, "");
            File downloadFile = new File(RuoYiConfig.getProfile() + fileRelativeName);
            //下载文件
            String extName = FileUtil.extName(downloadFile);
            String appName = appInfo.getName();
            String suffix = "." + extName;
            if (!appName.endsWith(suffix)) {
                appName = appName + suffix;
            }
            downloadFile(downloadFile, appName, response);
        }
    }
}
